<script lang="ts" setup>
import { ElImage } from 'element-plus'
import { getFileUrl } from '~/api/file'
import { getbxjkxllmDetail, getbxjkxllmList, getdslmList, getgblmList, getsqbxjkList, getsxrbDetail, getsxrbList } from '~/api/home'
import { decode } from '~/utils/base/dataEncry'

const router = useRouter()
const TJlist = ref<any[]>([])
const list = ref<any[]>([])
const fileData = ref({})
const fileType = ref()
const nowImg = ref()
const nowContents = ref()
const nowName = ref()
const title = ref('百姓健康系列栏目')
const routePath = [{ name: '首页', path: '/' }, { name: title, path: '/peopleHealth/peopleHealthSeries' }, { name: '详情', path: '' }]
const route = useRoute()
const queryParams = reactive(
  {
    condition: [],
  },
)
const queryParams2 = reactive(
  {
    page: {
      rownumber: 3,
      pageNo: 1,
    },
    order: [{
      colName: 'release_time',
      orderType: 'desc',
    }],
    condition: [
      {
        colName: 'column_recommendation',
        ruleType: 'eq',
        value: '是',
      },
    ],
  },
)
// fileData.value = decode(route.query.data)
fileType.value = route.query.type
function getDetail() {
  const req = {
    condition: [
      {
        colName: 'id',
        ruleType: 'eq',
        value: route.params.id,
      },
    ],
  }
  if (route.query.ptUid) {
    req.condition = [
      {
        colName: 'uid',
        ruleType: 'eq',
        value: route.query.ptUid,
      },
    ]
  }
  // if (route.query.uid) {
  //   req.condition = [{

  //     colName: 'uid',
  //     ruleType: 'eq',
  //     value: route.query.uid,
  //   }]
  // }
  const queryParams = {}
  if (fileType.value === '《陕西日报》专版') {
    getsxrbList(req).then((res) => {
      fileData.value = res.data[0]
      queryParams.condition = [{ colName: 'pt_uid', ruleType: 'eq', value: fileData.value.pt_uid || fileData.value.uid }]
      getsxrbDetailData(queryParams)
    })
  }
  else if (fileType.value === '《陕西老年健康报》专版') {
    getbxjkxllmList(req).then((res) => {
      fileData.value = res.data[0]
      queryParams.condition = [{ colName: 'pt_uid', ruleType: 'eq', value: fileData.value.pt_uid || fileData.value.uid }]
      getlnjkbDetailData(queryParams)
    })
    getlnjkbDetailData(req)
  }
  else if (fileType.value === '电视栏目') {
    getdslmList(req).then((res) => {
      fileData.value = res.data[0]
    })
  }
  else if (fileType.value === '广播栏目') {
    getgblmList(req).then((res) => {
      fileData.value = res.data[0]
    })
  }
  else if (fileType.value === '《三秦百姓健康》杂志') {
    getsqbxjkList(req).then((res) => {
      fileData.value = res.data[0]
    })
  }
}
if (route.params.id) {
  getDetail()
}
function getData() {
  // if (fileType.value === '《陕西日报》专版') {
  //   queryParams.condition = [{ colName: 'pt_uid', ruleType: 'eq', value: fileData.value.pt_uid ? fileData.value.pt_uid : fileData.value.uid }]
  //   getsxrbDetailData(queryParams)
  // }
  // else if (fileType.value === '《陕西老年健康报》专版') {
  //   queryParams.condition = [{ colName: 'pt_uid', ruleType: 'eq', value: fileData.value.pt_uid ? fileData.value.pt_uid : fileData.value.uid }]
  //   getlnjkbDetailData(queryParams)
  // }
  getdslmList(queryParams2).then((res) => {
    TJlist.value = res.data
  }).catch(() => {
  })
}
function getsxrbDetailData(queryParams) {
  getsxrbDetail(queryParams).then((res) => {
    // TJlist.value = res.data.slice(0, 3)
    fileData.value = res.data[0]
    nowImg.value = res.data[0].cover_file_name
    nowContents.value = res.data[0].contents
    nowName.value = res.data[0].title_name
    fileData.value.origin = res.data[0].origin
    list.value = res.data
  }).catch(() => {
  })
}
function getlnjkbDetailData(queryParams) {
  getbxjkxllmDetail(queryParams).then((res) => {
    // TJlist.value = res.data.slice(0, 3)
    fileData.value = res.data[0]

    nowImg.value = res.data[0].cover_file_name
    nowContents.value = res.data[0].contents
    nowName.value = res.data[0].title_name
    fileData.value.origin = res.data[0].origin
    list.value = res.data
  }).catch(() => {
  })
}
onMounted(() => {
  getData()
})
onUnmounted(() => {
  //  console.log('onUnmounted');
  // 如果body的display被设置成none,改成unset
  document.body.style.overflow = 'unset'
})
function clickItem(item) {
  fileType.value = item.classify_name.split('/')[1]
  fileData.value = item
  getData()
}

const { collectArticleMap } = storeToRefs(useUserStore())
function changeInfo(item) {
  nowImg.value = item.cover_file_name
  nowContents.value = item.contents
  nowName.value = item.title_name
  fileData.value.origin = item.origin
}
const itemName = computed(() => {
  return nowName.value
})

const htmlContainer = ref()
const imgSrcContainer = ref()
const imgSrc = ref('')
let observer
function addClickEventListeners() {
  if (!htmlContainer.value)
    return
  const imgs = htmlContainer.value.querySelectorAll('img')
  imgs.forEach((img) => {
    if (!img.hasAttribute('data-click-added')) {
      img.addEventListener('click', () => {
        imgSrc.value = img.getAttribute('src')
        console.log(imgSrc.value, imgSrcContainer.value)
        if (imgSrcContainer.value) {
          nextTick(() => {
            document.querySelector('#imgSrcContainer')?.querySelector('img')?.click()
          })
        }
      })
      img.setAttribute('style', 'pointer-events: unset;cursor: pointer')
      img.setAttribute('data-click-added', 'true')
    }
  })
}
function initObserver() {
  if (htmlContainer.value) {
    observer = new MutationObserver(addClickEventListeners)
    observer.observe(htmlContainer.value, { childList: true, subtree: true })
    addClickEventListeners() // 初始化时也添加事件监听器
  }
}

onUnmounted(() => {
  if (observer) {
    observer.disconnect()
  }
})

watch(nowContents, async () => {
  await nextTick()
  if (observer) {
    observer.disconnect()
    initObserver()
  }
  else {
    addClickEventListeners()
  }
}, { immediate: true })
</script>

<template>
  <div class="bg-[url('/img/index.png')] bg-#F7F9FD bg-no-repeat">
    <ClientOnly>
      <PublicSearch type="百姓健康系列栏目" />
      <PublicSearchDialog type="百姓健康系列栏目" />
      <div class="px-40">
        <div class="bg-#fff">
          <CommonPageContainer :title="title" :path="routePath">
            <div class="mt-20px flex justify-between">
              <div class="w-83% bg-#F7F9FD pr-5">
                <div class="flex items-center p-5 text-size-18px">
                  <div
                    class="ml-[-50px] h-40px w-40px flex cursor-pointer items-center justify-center rounded-md"
                    style="
                                background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);"
                    @click="router.back()"
                  >
                    <div class="h-18px w-18px flex items-center justify-center rounded-50% bg-#fff">
                      <span class="flex items-center -ml-2px" text="#0E9472">&lt;</span>
                    </div>
                  </div>
                  <div class="pl-5 text-#0E9472 font-700">
                    {{ title }}
                  </div>
                </div>
                <div v-if="(fileType === '《陕西日报》专版' || fileType === '《陕西老年健康报》专版') && fileData" class="pl-5">
                  <div class="px-10px text-size-32px text-#101010 font-500">
                    {{ fileData.periods }}
                  </div>
                  <div class="flex py-2">
                    <div class="mr-40px">
                      发布日期：{{ fileData.release_time }}
                    </div>
                    <div>
                      来源: {{ fileData.origin || fileData.publisher }}
                    </div>
                  </div>
                  <div class="flex justify-between">
                    <div class="w-48%">
                      <div class="demo-image__preview image-container">
                        <ElImage
                          :src="nowImg" :max-scale="7" :min-scale="0.2" hide-on-click-modal preview-teleported
                          :preview-src-list="[nowImg]" fit="cover"
                        />
                      </div>
                      <div>
                        <div>本期导读</div>
                        <div
                          v-for="(item, index) in list" :key="index" text="14px"
                          class="flex cursor-pointer items-center py-2" @click="changeInfo(item)"
                        >
                          <i
                            v-if="itemName === item.title_name"
                            class="i-ri:arrow-right-circle-line h-25px w-25px cursor-pointer text-#50bc8d"
                          />
                          <div :style="itemName === item.title_name ? 'color:#0E9472' : 'color:#333'">
                            {{ item.title_name }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div
                      ref="htmlContainer" class="h-750px w-50% overflow-y-scroll"
                      v-html="addControlsList(nowContents)"
                    />
                    <ElImage
                      id="imgSrcContainer" ref="imgSrcContainer" :src="imgSrc" :preview-src-list="[imgSrc]"
                      :initial-index="9999" :max-scale="7" :min-scale="0.2" hide-on-click-modal preview-teleported
                      style="display: none;"
                    />
                  </div>
                </div>
                <div v-else-if="fileType === '《三秦百姓健康》杂志' && fileData.pdf_file_name">
                  <PdfView :url="getFileUrl(fileData.pdf_file_name)" />
                </div>
                <div v-else-if="fileType === '电视栏目' || fileType === '广播栏目'">
                  <div class="px-10px text-size-32px text-#101010 font-500">
                    {{ fileData.title_name }}
                  </div>
                  <div class="flex py-2">
                    <div class="mr-40px">
                      发布日期：{{ fileData.release_time }}
                    </div>
                    <div>
                      来源: {{ fileData.origin || fileData.publisher }}
                    </div>
                  </div>
                  <div v-html="addControlsList(fileData.contents)" />
                </div>
                <div
                  v-if="fileType !== '《陕西日报》专版' && fileData && fileData.id"
                  class="flex items-center justify-center pb-46px pt-65px" text="16px #101010"
                >
                  <div
                    class="mr-14px h-42px w-100px flex cursor-pointer items-center justify-center bg-white"
                    @click="changeArticleCollect(fileData.uid)"
                  >
                    <i
                      class="i-carbon:favorite-filled mr-12px inline-block text-20px"
                      :class="{ 'text-red': collectArticleMap[fileData.uid], 'text-#555': !collectArticleMap[fileData.uid] }"
                    />
                    <span>{{ collectArticleMap?.[fileData.uid] ? '已收藏' : '收藏' }}</span>
                  </div>
                  <div class="h-42px w-100px flex cursor-pointer items-center justify-center bg-white" @click="copyUrl">
                    <img class="pr-12px" src="/img/share.png" alt="">
                    分享
                  </div>
                </div>
                <CommentSection
                  v-if="fileData && fileData.uid && fileData.enable_comments === '是'" :uid="fileData.uid"
                  :title="fileData.title_name"
                />
              </div>
              <div class="w-15%">
                <div>
                  <div
                    class="h-40px flex items-center rounded-tl rounded-tr px-10px py-5px"
                    style="background: linear-gradient(159.97deg, rgba(206,234,158,1) -140.78%,rgba(53,179,137,1) 89.45%);"
                  >
                    <img src="/img/tj.png" alt="">
                    <div class="pl-15px" text="#fff 16px">
                      推荐
                    </div>
                  </div>
                  <div class="rounded-bl rounded-br px-10px py-5px" border="2px solid #50bc8d">
                    <div
                      v-for="item in TJlist" :key="item.id" class="cursor-pointer" hover="text-#0E9472"
                      @click="clickItem(item)"
                    >
                      <img :src="item.cover_file_name" alt="">
                      <div class="py-10px" text="14px">
                        {{ item.title_name }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </CommonPageContainer>
        </div>
      </div>
    </ClientOnly>
  </div>
</template>

<style>
.image-container {
  position: relative;
  overflow: hidden;
  /* 防止滚动 */
}
</style>
